<template>
  <div class="user-add">
    <el-form :model="formData" label-width="100px" status-icon>
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号：" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
       <!-- <el-form-item label="角色：" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio :label="1">普通用户</el-radio>
          <el-radio :label="0">管理员</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item label="状态：" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="0">禁用</el-radio>
          <el-radio :value="1">启用</el-radio>
        </el-radio-group>
      </el-form-item>  -->
       <el-form-item label="性别：" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio :value="0">保密</el-radio>
          <el-radio :value="1">女</el-radio>
          <el-radio :value="2">男</el-radio>
        </el-radio-group>
      </el-form-item> 
      <el-form-item label="用户头像：" prop="avatar">
        <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :headers="uploadHeaders"
        >
    <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
  <div style="margin-left: 20px; font-size: 14px; color: #666;">
      支持格式：JPG、PNG、GIF、WEBP<br/>
      大小不超过：2MB
    </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">新增用户</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
 import { ref } from 'vue';
 import { ElMessage } from 'element-plus';
 import { Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus'
import axios from 'axios'
axios.defaults.baseURL = "http://localhost:8080";


const token = sessionStorage.getItem('token');
// 定义 upload 的 headers
const uploadHeaders = ref({
  Authorization: `${token}` 
});
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  formData.value.avatar = response.data; 
};
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 支持的文件类型列表
  const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  // 最大允许上传大小（单位：MB）
  const maxSizeMB = 2;

  // 检查文件类型是否符合要求
  if (!validTypes.includes(rawFile.type)) {
    ElMessage.error('上传头像图片只支持 JPG、PNG、GIF、WEBP 格式!');
    return false;
  }

  // 检查文件大小是否在限制内
  if (rawFile.size / 1024 / 1024 > maxSizeMB) {
    ElMessage.error(`上传头像图片大小不能超过 ${maxSizeMB}MB!`);
    return false;
  }

  return true;
};

const submitForm = async() => {
  console.log('提交表单数据:', formData.value);
  const token = sessionStorage.getItem('token'); 
   try {
    const res = await axios.post('/admin/add', formData.value,{
    headers: {
    Authorization: `${token}`
      }
    }
  )
    if (res.data.code === 0) {  
      ElMessage.success('新增成功')
      resetForm()
    } else {
      ElMessage.error(res.data.message || '新增失败')
    }
  } catch (err) {
    ElMessage.error('网络错误，请稍后再试')
    console.error(err)
  }
};

const formData = ref({
  username: '',
  phone: '',
  email: '',
  gender: 0,
  status: 0,
  avatar: ''
});
const resetForm = () => {
  formData.value = {
    username: '',
    phone: '',
    email: '',
    gender: 0,
    status: 0,
    avatar: ''
  };
};
</script>

<style scoped>
.user-add {
  width: 600px;
  margin: 0 0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>